<template>
  <view class="container position-relative">
    <image
      @click="toPage('/filePage/pages/cart/cart')"
      :src="baseUrl + '/static/cart2.png'"
      mode=""
      style="
        position: fixed;
        right: 50rpx;
        bottom: 50rpx;
        width: 100rpx;
        height: 100rpx;
        z-index: 100;
      "
    ></image>
    <view class="bg-to-right" style="height: 210rpx">
      <kg-custom :isBack="false" bgColor="bg-to-right">
        <block slot="left">
          <view
            class="text-17 padding-left-sm text-bold flex justify-start align-center"
          >
            <view class="margin-left-xs margin-right-xs text-221815">
              佑选商城
            </view>
          </view>
        </block>
      </kg-custom>
    </view>
    <view
      class="bg-white padding-sm"
      style="
        border-top-left-radius: 46rpx;
        border-top-right-radius: 46rpx;
        margin-top: -46rpx;
      "
    >
      <view
        @click="toPage('/filePage/pages/goods-list/goods-list')"
        class="flex justify-start align-center bg-F4F4F4 padding-left round"
        style="height: 78rpx"
      >
        <image
          :src="baseUrl + '/static/search_for.png'"
          mode=""
          style="width: 25rpx; height: 25rpx"
        >
        </image>
        <input
          type="text"
          value=""
          disabled
          class="text-13 f-grow1 padding-left-sm"
          placeholder="搜索商品名称"
        />
      </view>
      <view class="text-15 flex justify-start align-center margin-top-sm">
        <scroll-view
          scroll-x
          class="bg-white nav text-666"
          style="width: calc(100% - 87rpx)"
          scroll-with-animation
          :scroll-left="scrollLeft"
        >
          <!-- 	<view class="cu-item" :class="TabCur==999?'color cur text-bold':''" @tap="tabSelect" :data-id="999">
						首页
					</view> -->
          <view
            class="cu-item"
            :class="index == TabCur ? 'color cur text-bold' : ''"
            v-for="(item, index) in classification1"
            @click="tabSelect(index, item.id)"
          >
            {{ item.name }}
          </view>
        </scroll-view>
        <view
          class="color"
          @click="
            toPage('/filePage/pages/classification/classification?type=1')
          "
          style="min-width: 87rpx"
        >
          全部
        </view>
      </view>
      <swiper
        class="padding-top-sm padding-bottom-sm"
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        circular="true"
        :duration="1000"
        indicator-color="#F4F4F4"
        indicator-active-color="#ED7200"
      >
        <swiper-item v-for="item in banners" @click="toLink(item)">
          <image
            class="width-sub height-sub radius10"
            :src="item.pic"
            mode=""
          ></image>
        </swiper-item>
      </swiper>
      <view class="position-relative" v-if="classification2.length > 0">
        <swiper
          class="classification-swiper"
          circular="true"
          @change="change"
          :duration="1000"
          indicator-color="#F4F4F4"
          indicator-active-color="#ED7200"
        >
          <!-- <swiper-item v-for="item in 3">
						<view class="cu-list flex justify-start flex-wrap">
							<view v-for="item in 10" style="width: 20%;padding: 19rpx;" class="cu-item text-sm flex flex-direction justify-center align-center">
								<image :src="baseUrl + '/static/fingerprint.png'" mode="" style="width: 48rpx;height: 48rpx;"></image>
								<view class="margin-top-sm">
									装指纹锁
								</view>
							</view>
						</view>
					</swiper-item> -->
          <swiper-item v-for="item in classification2">
            <view class="cu-list flex justify-start flex-wrap">
              <view
                @click="
                  toPage(
                    '/filePage/pages/goods-list/goods-list?secondCategoryId=' +
                      im.id
                  )
                "
                v-for="im in item"
                style="width: 20%; padding: 19rpx"
                class="cu-item text-sm flex flex-direction justify-center align-center"
              >
                <image
                  :src="im.icon"
                  mode=""
                  style="width: 48rpx; height: 48rpx"
                ></image>
                <view class="margin-top-sm">
                  {{ im.name }}
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>

        <view class="flex dots">
          <view
            class="dot"
            :class="[current == i ? 'curr-dot' : '']"
            v-for="(d, i) in classification2"
            :key="i"
          >
          </view>
        </view>
      </view>
    </view>

    <view
      class="margin-sm padding-sm bg-white radius10"
      v-if="GroupBuy.length > 0"
    >
      <view class="flex justify-between align-center">
        <view class="flex justify-start align-center">
          <image
            :src="baseUrl + '/static/group.png'"
            mode=""
            style="width: 46rpx; height: 34rpx"
          >
          </image>
          <view class="text-17 text-221815 margin-left-xs text-bold">
            超值团购
          </view>
        </view>
        <view
          class="flex justify-start align-center"
          @click="toPage('/filePage/pages/goods-list/goods-list?groupStatus=1')"
        >
          <view class="text-sm text-999 margin-right-xs"> 更多团购 </view>
          <image
            :src="baseUrl + '/static/right.png'"
            mode=""
            style="width: 14rpx; height: 14rpx"
          >
          </image>
        </view>
      </view>
      <scroll-view
        scroll-x="true"
        class="margin-top-sm nav"
        scroll-with-animation
      >
        <view class="flex justify-start">
          <view
            class="position-relative"
            style="width: 200rpx; min-width: 200rpx"
            v-for="(item, index) in GroupBuy"
            :class="{ 'margin-left-xs': index != 0 }"
            @click="
              toPage(
                '/filePage/pages/goods-detail/goods-detail?id=' + item.productId
              )
            "
          >
            <view
              class="text-11 zIndex flex justify-center align-center text-white"
              :style="
                'background-image: url(' +
                baseUrl +
                '/static/shop_bg.png);background-size: 100% 100%;width: 82rpx;height: 34rpx;position: absolute;left: 15rpx;top: 152rpx'
              "
            >
              {{ item.discount }}折
            </view>
            <image
              :src="item.pic"
              mode=""
              class="width-sub radius10"
              style="height: 200rpx"
            ></image>
            <view
              class="text-bold text-sm text-333 width-sub text-cut padding-left-xs padding-right-xs margin-top-xs"
            >
              {{ item.productName }}
            </view>
            <view class="color text-sm margin-top-sm">
              ¥{{ parseFloat(item.groupPrice / 100).toFixed(2) }}
            </view>
            <view class="text-sm text-999 text-delete margin-top-sm">
              ¥{{ parseFloat(item.price / 100).toFixed(2) }}
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view
      class="text-17 text-221815 margin-left-sm margin-right-sm text-bold margin-bottom-xs"
      style="margin-top: 50rpx"
    >
      推荐商品
    </view>
    <view
      class="flex flex-wrap justify-start margin-left-sm margin-right-sm margin-bottom-sm"
    >
      <view
        @click.stop="
          toPage('/filePage/pages/goods-detail/goods-detail?id=' + item.id)
        "
        class="position-relative bg-white radius10 margin-top-sm"
        style="width: 348rpx; min-width: 348rpx"
        v-for="(item, index) in list"
        :class="{ 'margin-left14': index % 2 }"
      >
        <view
          class="text-11 zIndex flex justify-center align-center text-white"
          :style="
            'background-image: url(' +
            baseUrl +
            '/static/shop_bg2.png);background-size: 100% 100%;width: 70rpx;height: 36rpx;position: absolute;left: 0;top: 0'
          "
        >
          新品
        </view>
        <image
          :src="item.pic"
          mode=""
          class="width-sub radius-t-l radius-t-r"
          style="height: 348rpx"
        ></image>
        <view class="padding-sm">
          <view class="text-cut text-15 text-333">
            {{ item.name }}
          </view>
          <view class="color text-sm margin-top-sm">
            ¥{{ parseFloat(item.price / 100).toFixed(2) }}
          </view>
          <view class="flex justify-between align-center margin-top-sm">
            <view class="text-sm text-999 text-delete">
              ¥{{ parseFloat(item.originalPrice / 100).toFixed(2) }}
            </view>
            <image
              @click.stop="showSku(item.id)"
              :src="baseUrl + '/static/cart.png'"
              mode=""
              style="width: 28rpx; height: 28rpx"
            ></image>
          </view>
        </view>
      </view>
    </view>
    <uni-load-more :status="loading" />
    <view class="cu-modal" :class="modalName == 'ModalAuthor' ? 'show' : ''">
      <view class="cu-dialog bg-white">
        <view class="cu-bar justify-end">
          <view class="content">提示</view>
        </view>
        <view class="padding-xl text-20"> 请先授权登录 </view>
        <view class="flex justify-between align-center padding text-lg">
          <view
            @click="hideModal"
            class="bg-D7D7D7 text-gray radius5"
            style="padding: 32rpx 96rpx"
          >
            取消
          </view>
          <button
            v-if="canIUseProfile == false"
            open-type="getUserInfo"
            @getuserinfo="getUserInfo"
            class="bg-color text-white radius5"
            style="padding: 32rpx 96rpx"
          >
            确定
          </button>
          <button
            v-else
            @tap="getUserInfo"
            class="bg-color text-white radius5"
            style="padding: 32rpx 96rpx"
          >
            确定
          </button>
        </view>
      </view>
    </view>
    <view class="cu-modal" :class="modalName == 'ModalAuthor' ? 'show' : ''">
      <view class="cu-dialog bg-white">
        <view class="cu-bar justify-end">
          <view class="content">提示</view>
        </view>
        <view class="padding-xl text-20"> 请先授权登录 </view>
        <view class="flex justify-between align-center padding text-lg">
          <view
            @click="hideModal"
            class="bg-D7D7D7 text-gray radius5"
            style="padding: 32rpx 96rpx"
          >
            取消
          </view>
          <button
            v-if="canIUseProfile == false"
            open-type="getUserInfo"
            @getuserinfo="getUserInfo"
            class="bg-color text-white radius5"
            style="padding: 32rpx 96rpx"
          >
            确定
          </button>
          <button
            v-else
            @tap="getUserInfo"
            class="bg-color text-white radius5"
            style="padding: 32rpx 96rpx"
          >
            确定
          </button>
        </view>
      </view>
    </view>
    <view class="cu-modal" :class="{ show: isShow }">
      <view class="cu-dialog bg-white">
        <view class="cu-bar justify-end">
          <view class="content">提示</view>
        </view>
        <view class="padding-xl text-20"> 获取用户手机号 </view>
        <view class="flex justify-between align-center padding text-lg">
          <view
            @click="isShow = false"
            class="bg-D7D7D7 text-gray radius5"
            style="padding: 32rpx 96rpx"
          >
            取消
          </view>
          <button
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
            class="bg-color text-white radius5"
            style="padding: 32rpx 96rpx"
          >
            确定
          </button>
        </view>
      </view>
    </view>
    <!--底部 sku 选择弹窗 -->
    <wui-specification
      :goodsInfo="goodsInfo"
      btnType="1"
      :show="show"
      @select="selectSku"
      @close="hideSku"
    >
    </wui-specification>
  </view>
</template>

<script>
import BetterPull from "@/common/libs/BetterPull";
export default {
  mixins: [
    BetterPull({
      async getPage(page, done) {
        this.loading = "loading";
        const [err, res] = await this.$get(
          this.$api.home_recommendProductList,
          {
            pageNum: page,
            pageSize: 10,
          }
        );
        if (res) {
          // console.log(res)
          var data = res.data.list;
          this.total = res.data.total;
          done(data);
          if (data.length < 10) {
            this.loading = "noMore";
          } else {
            this.loading = "more";
          }
          // console.log(this.loading)
        }
        if (err) {
          done([]);
          this.loading = "noMore";
        }
      },
    }),
  ],
  data() {
    return {
      current: 0,
      TabCur: 0,
      scrollLeft: 0,
      baseUrl: this.$config.baseUrl,
      banners: [],
      classification1: [],
      classification2: [],
      loading: "more",
      GroupBuy: [],
      modalName: null,
      latitude: "",
      longitude: "",
      canIUseProfile: false,
      show: false,
      goodsInfo: {},
      selectInfo: {
        difference: "请选择规格",
      }, //存放最后选中的商品
      classification1Id: "",
      isShow: false,
      session_key: "",
      phoneNumber: "",
	  recommendCode:''
    };
  },
  onLoad() {
    if (wx.getUserProfile) {
      // console.log("--check getUserProfile--OK");
      this.canIUseProfile = true;
    }
    this.getBanner();
    this.getClassification();
    this.getGroupBuy();
  },
  onPullDownRefresh() {
  	this.getBanner();
  	this.getClassification();
  	this.getGroupBuy();
  },
  onShow() {
	  if(uni.getStorageSync('scene')){
	  	this.recommendCode  = uni.getStorageSync('scene')
	  }
    let that = this;
    // if (uni.getStorageSync('mobile')) {
    // 	this.phoneNumber = uni.getStorageSync('mobile')
    // }
    uni.getLocation({
      type: "gcj02",
      success: function (res) {
        that.latitude = res.latitude;
        that.longitude = res.longitude;
        // that.getFlag()
        // uni.getStorage({
        //   key: "userId",
        //   success: function () {
        //     that.getUser();
        //     // if (!that.phoneNumber) {
        //     // 	that.isShow = true
        //     // }
        //   },
        //   fail: function () {
        //     that.modalName = "ModalAuthor";
        //   },
        // });
      },
      fail: function (err) {
        that.$util.msg("请允许定位");
        setTimeout(() => {
          uni.switchTab({
            url: "/pages/home/home",
          });
        }, 1500);
      },
    });
  },
  methods: {
    // async getFlag() {
    // 	const [err, res] = await this.$get(this.$api.hiddenFlag);
    // 	if (res) {
    // 		// this.banners = res.data;
    // 		uni.setStorage({
    // 			key:'is_flag',
    // 			data:res.data
    // 		})
    // 		// console.log(res)
    // 	}
    // },
   showSku(e) {
   	let that = this;
   	this.goodsInfo = {};
   
   	if (this.latitude) {
   		uni.getStorage({
   			key: "userId",
   			success: function() {
   				that.getInfo(e);
   			},
   			fail: function() {
   				// #ifdef MP-WEIXIN
   				that.modalName = "ModalAuthor";
   				// #endif
   				// #ifdef APP-PLUS
   				uni.navigateTo({
   					url: "/pages/login/login",
   				});
   				// #endif
   				
   			},
   		});
   	} else {
   		this.modalName = "ModalAddress";
   	}
   },
    hideSku(e) {
      this.show = false;
      this.selectInfo = e;
      // console.log(e)
    },
    selectSku(options) {
      //点击sku弹窗中的加入购物车或结算按钮
      this.show = false;
      this.selectInfo = options;
      this.addCart();
    },
    async getInfo(e) {
      const [err, res] = await this.$get(this.$api.product_detail, {
        id: e,
      });
      if (res) {
        this.show = true;
        this.goodsInfo = res.data;
      }
    },
    async addCart() {
      // console.log(this.selectInfo)
      const [err, res] = await this.$post(this.$api.car_add, {
        attributes: this.selectInfo.difference,
        buyNum: this.selectInfo.num,
        price: this.selectInfo.price,
        productId: this.goodsInfo.id,
        productImg: this.selectInfo.pic
          ? this.selectInfo.pic
          : this.goodsInfo.pic,
        productName: this.goodsInfo.name,
        shopId: this.goodsInfo.shopId,
        shopImg: this.goodsInfo.shopImg,
        shopName: this.goodsInfo.shopName,
        skuId: this.selectInfo.id,
      });
      if (res) {
        // console.log(res)
        this.$util.msg("加入购物车成功");
        // setTimeout(() => {
        // 	uni.navigateBack()
        // }, 1500)
      }
    },
    tabSelect(e, id) {
      this.TabCur = e;
      this.classification1Id = id;
      this.scrollLeft = (e - 1) * 60;
      this.getClassification2();
    },
    async getUserInfo() {
      let that = this;
      // this.hideModal()
      this.modalName = null;
      if (that.canIUseProfile == false) {
        uni.login({
          provider: "weixin",
          success: function (loginRes) {
            console.log(loginRes);
            uni.getUserInfo({
              provider: "weixin",
              success: function (infoRes) {
                console.log(infoRes);
                that.getLogin(
                  loginRes.code,
                  res.userInfo.nickName,
                  res.userInfo.avatarUrl
                );
              },
            });
          },
        });
      } else {
        console.log(1111);
        uni.getUserProfile({
          desc: "Wexin",
          success: function (res) {
            console.log("wx.getUserProfile=>用户允许了授权");
            console.log(res.userInfo);
            // console.log( res.rawData );
            console.log(res.signature);
            console.log(res.encryptedData);
            console.log(res.iv);
            uni.login({
              provider: "weixin",
              success: function (loginRes) {
                console.log(loginRes);
                that.getLogin(
                  loginRes.code,
                  res.userInfo.nickName,
                  res.userInfo.avatarUrl
                );
              },
            });
          },
          fail(rs) {
            console.log(rs);
          },
        });
      }
    },
    async getLogin(code, nickName, avatarUrl) {
      uni.showLoading({
        title: "正在登录",
        mask: true,
      });
	  const data = {
	  	code: code,
	  	nickname: nickName,
	  	headimg: avatarUrl,
	  	latitude: this.latitude,
	  	longitude: this.longitude,
	  };
	  if (this.recommendCode) {
	  	data["recommendCode"] = this.recommendCode;
	  }
      const [err, res] = await this.$post(this.$api.loginWX,data);
      if (res) {
        this.isShow = true;
        this.session_key = res.data.session_key;
        uni.setStorage({
          key: "session_key",
          data: res.data.session_key,
        });
        // console.log(res)
        uni.setStorage({
          key: "token",
          data: res.data.openid,
        });
        uni.setStorage({
          key: "userId",
          data: res.data.userId,
        });
		uni.setStorage({
			key: "openid",
			data: res.data.openid,
		});
        uni.hideLoading();
        this.getBanner();
        this.getClassification();
        this.getGroupBuy();
        this.getUser();
        this.list = [];
        uni.startPullDownRefresh();
        this.$util.msg(res.message);
      }
    },
    hideModal() {
      this.modalName = null;
      uni.switchTab({
        url: "/pages/home/home",
      });
    },
    change(event) {
      let current = event.detail.current;
      this.current = current;
    },
    toPage(url) {
      let that = this;
      uni.getStorage({
        key: "userId",
        success: function () {
          that.$util.openNewPage(url);
          // if (!that.phoneNumber) {
          // 	that.isShow = true
          // } else {
          // 	that.$util.openNewPage(url)
          // }
        },
        fail: function () {
          // #ifdef MP-WEIXIN
          that.modalName = "ModalAuthor";
          // #endif

          // #ifdef APP-PLUS
          uni.navigateTo({
            url: "/pages/login/login",
          });
          // #endif
        },
      });
    },
    async getBanner() {
      const [err, res] = await this.$get(this.$api.home_getAdvertisementList, {
        adPositionType: 3,
      });
      if (res) {
        this.banners = res.data;
        // console.log(res)
      }
    },
    async getClassification() {
      const [err, res] = await this.$get(this.$api.home_categoryTreeList, {
        type: 1,
      });
      if (res) {
        this.classification1 = res.data;
        // if(this.classification1.length>0){
        // 	this.classification1Id = this.classification1[0].id
        // 	this.getClassification2()
        // }
        if (this.classification1.length > 0) {
          this.classification1Id = this.classification1[0].id;
          this.getClassification2();
        }
      }
    },
    async getClassification2() {
      const [err, res] = await this.$get(this.$api.home_productCateList, {
        parentId: this.classification1Id,
        type: 1,
      });
      if (res) this.classification2 = this.$util.spArr(res.data, 10);
    },
    async getGroupBuy() {
      const [err, res] = await this.$get(
        this.$api.product_groupBuyProductList,
        {
          pageNum: 1,
          pageSize: 15,
        }
      );
      if (res) {
        this.GroupBuy = res.data.list;
        // console.log(res)
      }
    },
    async getUser() {
      const [err, rs] = await this.$get(this.$api.userDetail);
      if (rs) {
        // console.log(rs)
        uni.setStorageSync("userInfo", rs.data);
      }
    },
   toLink(e) {
   	let that = this;
   
   	uni.getStorage({
   		key: "userId",
   		success: function() {
   			if (e.redirectType == 1) {
   				// #ifdef APP-PLUS
   				plus.runtime.openURL(encodeURI(e.redirectUrl), function (res) {
   				  console.log(res);
   				});
   				// #endif
   				// #ifdef MP-WEIXIN
   				that.$util.openNewPage(
   				  "/filePage/pages/open-link/open-link?url=" + e.redirectUrl
   				);
   				// #endif
   			} else {
   			    that.$util.openNewPage(
   					"/filePage/pages/goods-detail/goods-detail?id=" + e.redirectUrl
   				);
   			}
   		},
   		fail() {
   			
   			// #ifdef MP-WEIXIN
   			that.modalName = "ModalAuthor";
   			// #endif
   			// #ifdef APP-PLUS
   			uni.navigateTo({
   				url: "/pages/login/login",
   			});
   			// #endif
   		}
   
   	})
   },
    async getPhoneNumber(e) {
      this.isShow = false;
      console.log(e);
      var iv = e.detail.iv;
      var encryptedData = e.detail.encryptedData;
      var session_key;
      if (uni.getStorageSync("session_key")) {
        session_key = uni.getStorageSync("session_key");
      } else {
        session_key = this.session_key;
      }
      const data = {
        session_key,
        iv,
        encryptedData,
      };
      const [err, rs] = await this.$get(this.$api.getWXPhone, data);
      if (rs) {
        this.$util.msg(rs.message);
        this.phoneNumber = rs.data.mobile;
        uni.setStorageSync("mobile", rs.data.mobile);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.classification-swiper {
  height: 318rpx;
}

.dots {
  display: flex;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 20rpx;

  .dot {
    width: 30rpx;
    height: 4rpx;
    border-radius: 6rpx;
    background-color: #d6d6d6;
    margin-right: 8rpx;
  }

  .curr-dot {
    width: 30rpx;
    height: 4rpx;
    border-radius: 6rpx;
    background-color: #ed7200;
  }
}

.margin-left14 {
  margin-left: 14rpx;
}
</style>
